<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Encoding," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="今天遇到一堆MySQL 中文乱码的问题 ，总体来说分为数据库层面，Tomcat层面，web表示层面。 数据库层面先是MySQL数据库中文乱码问题，大概样子如下：      然后自我感觉这件事情不就是改下字段的编码吗，那就改一下呗如图，我更改了Encoding        然后发现事情并没有那简单，于是开始上网查解决方案，网上说需要修改/etc/my.cnf(此配置文件对于mac后缀是.cnf，对">
<meta name="keywords" content="Encoding">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL解决中文乱码之全套方案">
<meta property="og:url" content="http://zhangk.top/WebEncoding/index.html">
<meta property="og:site_name" content="Zhangke&#39;s blog">
<meta property="og:description" content="今天遇到一堆MySQL 中文乱码的问题 ，总体来说分为数据库层面，Tomcat层面，web表示层面。 数据库层面先是MySQL数据库中文乱码问题，大概样子如下：      然后自我感觉这件事情不就是改下字段的编码吗，那就改一下呗如图，我更改了Encoding        然后发现事情并没有那简单，于是开始上网查解决方案，网上说需要修改/etc/my.cnf(此配置文件对于mac后缀是.cnf，对">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20171022002712080?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171022003238367?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171022010537041?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171022010832033?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171022010927654?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2017-10-22T04:24:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MySQL解决中文乱码之全套方案">
<meta name="twitter:description" content="今天遇到一堆MySQL 中文乱码的问题 ，总体来说分为数据库层面，Tomcat层面，web表示层面。 数据库层面先是MySQL数据库中文乱码问题，大概样子如下：      然后自我感觉这件事情不就是改下字段的编码吗，那就改一下呗如图，我更改了Encoding        然后发现事情并没有那简单，于是开始上网查解决方案，网上说需要修改/etc/my.cnf(此配置文件对于mac后缀是.cnf，对">
<meta name="twitter:image" content="http://img.blog.csdn.net/20171022002712080?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'ZY6JY6ZPM9',
      apiKey: '5d7498bc5ed50652590b1467b96af99c',
      indexName: 'test_zhangke',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zhangk.top/WebEncoding/"/>





  <title>MySQL解决中文乱码之全套方案 | Zhangke's blog</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhangke's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://zhangk.top/WebEncoding/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhangke">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhangke's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MySQL解决中文乱码之全套方案</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-21T23:49:22+08:00">
                2017-10-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Encoding/" itemprop="url" rel="index">
                    <span itemprop="name">Encoding</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/WebEncoding/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="WebEncoding/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/WebEncoding/" class="leancloud_visitors" data-flag-title="MySQL解决中文乱码之全套方案">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>今天遇到一堆MySQL <strong>中文</strong>乱码的问题 ，总体来说分为<strong>数据库</strong>层面，<strong>Tomcat</strong>层面，<strong>web表示</strong>层面。</p>
<h2 id="数据库层面"><a href="#数据库层面" class="headerlink" title="数据库层面"></a>数据库层面</h2><p>先是MySQL数据库中文乱码问题，大概样子如下：  </p>
<p><img src="http://img.blog.csdn.net/20171022002712080?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="问号">  </p>
<p>然后自我感觉这件事情不就是改下字段的编码吗，那就改一下呗<br>如图，我更改了Encoding  </p>
<p><img src="http://img.blog.csdn.net/20171022003238367?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="字段编码">    </p>
<p>然后发现事情并没有那简单，于是开始上网查解决方案，网上说需要修改<code>/etc/my.cnf</code>(此配置文件对于mac后缀是<code>.cnf</code>，对于Windows是<code>.ini</code>)。所以漫漫找寻之路开始了，最后连Linux查询find语句也试了就是找不到，终于在几篇文章里查到Mac上的MySQL没有<code>my.cnf</code>配置文件，好吧，继续寻找解决方案，有人说MySQL下的support-file中找一个<code>.cnf</code>复制一下再改；里面的东西，然而我连<code>.cnf</code>文件都没有找到。最后采用一位网友的办法，直接在<code>/etc</code>目录下  <code>vim my.cnf</code>新建一个文件，在此附上我修改过的文件里面内容，在<code>[mysqld]</code> 之后增加了一行 <code>collation-server = utf8_general_ci</code>  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"># Example MySQL config file for medium systems.</div><div class="line">  #</div><div class="line">  # This is for a system with little memory (32M - 64M) where MySQL plays</div><div class="line">  # an important part, or systems up to 128M where MySQL is used together with</div><div class="line">  # other programs (such as a web server)</div><div class="line">  #</div><div class="line">  # MySQL programs look for option files in a set of</div><div class="line">  # locations which depend on the deployment platform.</div><div class="line">  # You can copy this option file to one of those</div><div class="line">  # locations. For information about these locations, see:</div><div class="line">  # http://dev.mysql.com/doc/mysql/en/option-files.html</div><div class="line">  #</div><div class="line">  # In this file, you can use all long options that a program supports.</div><div class="line">  # If you want to know which options a program supports, run the program</div><div class="line">  # with the &quot;--help&quot; option.</div><div class="line">  # The following options will be passed to all MySQL clients</div><div class="line">  [client]</div><div class="line">  default-character-set=utf8</div><div class="line">  #password   = your_password</div><div class="line">  port        = 3306</div><div class="line">  socket      = /tmp/mysql.sock</div><div class="line">  # Here follows entries for some specific programs</div><div class="line">  # The MySQL server</div><div class="line">  [mysqld]</div><div class="line">  character-set-server=utf8</div><div class="line">  default-storage-engine = INNODB</div><div class="line">  collation-server = utf8_general_ci</div><div class="line">  init_connect=&apos;SET NAMES utf8&apos;</div><div class="line">  port        = 3306</div><div class="line">  socket      = /tmp/mysql.sock</div><div class="line">  skip-external-locking</div><div class="line">  key_buffer_size = 16M</div><div class="line">  max_allowed_packet = 1M</div><div class="line">  table_open_cache = 64</div><div class="line">  sort_buffer_size = 512K</div><div class="line">  net_buffer_length = 8K</div><div class="line">  read_buffer_size = 256K</div><div class="line">  read_rnd_buffer_size = 512K</div><div class="line">  myisam_sort_buffer_size = 8M</div><div class="line">  character-set-server=utf8</div><div class="line">  init_connect=&apos;SET NAMES utf8&apos;</div><div class="line"># Don&apos;t listen on a TCP/IP port at all. This can be a security enhancement,</div><div class="line"># if all processes that need to connect to mysqld run on the same host.</div><div class="line"># All interaction with mysqld must be made via Unix sockets or named pipes.</div><div class="line"># Note that using this option without enabling named pipes on Windows</div><div class="line"># (via the &quot;enable-named-pipe&quot; option) will render mysqld useless!</div><div class="line">#</div><div class="line">#skip-networking</div><div class="line"></div><div class="line">  # Replication Master Server (default)</div><div class="line">  # binary logging is required for replication</div><div class="line">  log-bin=mysql-bin</div><div class="line"></div><div class="line">    # binary logging format - mixed recommended</div><div class="line">    binlog_format=mixed</div><div class="line"></div><div class="line">      # required unique id between 1 and 2^32 - 1</div><div class="line">      # defaults to 1 if master-host is not set</div><div class="line">      # but will not function as a master if omitted</div><div class="line">      server-id   = 1</div><div class="line"></div><div class="line">    # Replication Slave (comment out master section to use this)</div><div class="line">    #</div><div class="line">    # To configure this host as a replication slave, you can choose between</div><div class="line">    # two methods :</div><div class="line">    #</div><div class="line">    # 1) Use the CHANGE MASTER TO command (fully described in our manual) -</div><div class="line">    #    the syntax is:</div><div class="line">    #</div><div class="line">    #    CHANGE MASTER TO MASTER_HOST=&lt;host&gt;, MASTER_PORT=&lt;port&gt;,</div><div class="line">    #    MASTER_USER=&lt;user&gt;, MASTER_PASSWORD=&lt;password&gt; ;</div><div class="line">    #</div><div class="line">    #    where you replace &lt;host&gt;, &lt;user&gt;, &lt;password&gt; by quoted strings and</div><div class="line">    #    &lt;port&gt; by the master&apos;s port number (3306 by default).</div><div class="line">    #</div><div class="line">    #    Example:</div><div class="line">    #</div><div class="line">    #    CHANGE MASTER TO MASTER_HOST=&apos;125.564.12.1&apos;, MASTER_PORT=3306,</div><div class="line">    #    MASTER_USER=&apos;joe&apos;, MASTER_PASSWORD=&apos;secret&apos;;</div><div class="line">    #</div><div class="line">    # OR</div><div class="line">    #</div><div class="line">    # 2) Set the variables below. However, in case you choose this method, then</div><div class="line">    #    start replication for the first time (even unsuccessfully, for example</div><div class="line">    #    if you mistyped the password in master-password and the slave fails to</div><div class="line">    #    connect), the slave will create a master.info file, and any later</div><div class="line">    #    change in this file to the variables&apos; values below will be ignored and</div><div class="line">    #    overridden by the content of the master.info file, unless you shutdown</div><div class="line">    #    the slave server, delete master.info and restart the slaver server.</div><div class="line">    #    For that reason, you may want to leave the lines below untouched</div><div class="line">    #    (commented) and instead use CHANGE MASTER TO (see above)</div><div class="line">    #</div><div class="line">    # required unique id between 2 and 2^32 - 1</div><div class="line">    # (and different from the master)</div><div class="line">    # defaults to 2 if master-host is set</div><div class="line">    # but will not function as a slave if omitted</div><div class="line">    #server-id       = 2</div><div class="line">    #</div><div class="line">    # The replication master for this slave - required</div><div class="line">    #master-host     =   &lt;hostname&gt;</div><div class="line">    #</div><div class="line">    # The username the slave will use for authentication when connecting</div><div class="line">    # to the master - required</div><div class="line">    #master-user     =   &lt;username&gt;</div><div class="line">    #</div><div class="line">    # The password the slave will authenticate with when connecting to</div><div class="line">    # the master - required</div><div class="line">    #master-password =   &lt;password&gt;</div><div class="line">    #</div><div class="line">    # The port the master is listening on.</div><div class="line">    # optional - defaults to 3306</div><div class="line">    #master-port     =  &lt;port&gt;</div><div class="line">    #</div><div class="line">    # binary logging - not required for slaves, but recommended</div><div class="line">    #log-bin=mysql-bin</div><div class="line"></div><div class="line">      # Uncomment the following if you are using InnoDB tables</div><div class="line">      #innodb_data_home_dir = /usr/local/mysql/data</div><div class="line">      #innodb_data_file_path = ibdata1:10M:autoextend</div><div class="line">      #innodb_log_group_home_dir = /usr/local/mysql/data</div><div class="line">      # You can set .._buffer_pool_size up to 50 - 80 %</div><div class="line">      # of RAM but beware of setting memory usage too high</div><div class="line">      #innodb_buffer_pool_size = 16M</div><div class="line">      #innodb_additional_mem_pool_size = 2M</div><div class="line">      # Set .._log_file_size to 25 % of buffer pool size</div><div class="line">      #innodb_log_file_size = 5M</div><div class="line">      #innodb_log_buffer_size = 8M</div><div class="line">      #innodb_flush_log_at_trx_commit = 1</div><div class="line">      #innodb_lock_wait_timeout = 50</div><div class="line"></div><div class="line">        [mysqldump]</div><div class="line">        quick</div><div class="line">        max_allowed_packet = 16M</div><div class="line"></div><div class="line">          [mysql]</div><div class="line">          no-auto-rehash</div><div class="line">          # Remove the next comment character if you are not familiar with SQL</div><div class="line">          #safe-updates</div><div class="line">          default-character-set=utf8</div><div class="line"></div><div class="line">        [myisamchk]</div><div class="line">        key_buffer_size = 20M</div><div class="line">        sort_buffer_size = 20M</div><div class="line">        read_buffer = 2M</div><div class="line">        write_buffer = 2M</div><div class="line"></div><div class="line">          [mysqlhotcopy]</div><div class="line">          interactive-timeout</div></pre></td></tr></table></figure>
<p>此时保存文件，再修改文件读写权限，将权限修改为664  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">sudo chmod 664 /etc/my.cnf</div></pre></td></tr></table></figure>
<p>之后再重启MySQL和配置文件就可以生效了。<br>然后完成之后，确实，如果你查一下MySQL的各种编码，确实都变成了UTF-8<br>通过以下命令  </p>
<p><img src="http://img.blog.csdn.net/20171022010537041?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="查数据库编码">    </p>
<p>然而~输入不了中文了，报错  </p>
<p><img src="http://img.blog.csdn.net/20171022010832033?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p>最后将当前数据库以及所有表所有字段都设置为UTF-8   </p>
<p><img src="http://img.blog.csdn.net/20171022010927654?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemt6azk2ODcx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述">   </p>
<p>惊喜的发现可以愉快的输入中文了~~<br>至此，数据库层面告一段落</p>
<h2 id="Tomcat层面"><a href="#Tomcat层面" class="headerlink" title="Tomcat层面"></a>Tomcat层面</h2><p>接下来我说的简略一些，如果URL请求采取GET方法，那么你的URL中可能会出现中文，所以需要在Tomcat配置文件里面设置编码方式。  </p>
<p>修改Tomcat下的<code>conf/server.xml</code>文件，找到如下代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&lt;Connector port=&quot;8080&quot; protocol=&quot;HTTP/1.1&quot;</div><div class="line">              connectionTimeout=&quot;20000&quot;</div><div class="line">              redirectPort=&quot;8443&quot; /&gt;</div></pre></td></tr></table></figure>
<p>  这段代码规定了Tomcat监听HTTP请求的端口号等信息。可以在这里添加一个属性：URIEncoding，将该属性值设置为UTF-8，<br>即可让Tomcat（默认ISO-8859-1编码）以UTF-8的编码处理get请求。更改后的代码如下所示： </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&lt;Connector port=&quot;8080&quot; protocol=&quot;HTTP/1.1&quot;</div><div class="line">		connectionTimeout=&quot;20000&quot;</div><div class="line">		 URIEncoding=&quot;UTF-8&quot;</div><div class="line">		  redirectPort=&quot;8443&quot; /&gt;</div></pre></td></tr></table></figure>
<h2 id="Web显示层面"><a href="#Web显示层面" class="headerlink" title="Web显示层面"></a>Web显示层面</h2><p>这里主要针对请求为POST方法的时候，你需要设置<code>web.xml</code> 文件，设置字符串过滤器  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">&lt;filter&gt;</div><div class="line">   &lt;filter-name&gt;characterEncodingFilter&lt;/filter-name&gt;</div><div class="line">   &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt;</div><div class="line">   &lt;init-param&gt;</div><div class="line">       &lt;param-name&gt;encoding&lt;/param-name&gt;</div><div class="line">       &lt;param-value&gt;UTF-8&lt;/param-value&gt;</div><div class="line">   &lt;/init-param&gt;</div><div class="line">   &lt;init-param&gt;</div><div class="line">       &lt;param-name&gt;forceEncoding&lt;/param-name&gt;</div><div class="line">       &lt;param-value&gt;true&lt;/param-value&gt;</div><div class="line">   &lt;/init-param&gt;</div><div class="line">&lt;/filter&gt;</div><div class="line">&lt;filter-mapping&gt;</div><div class="line">   &lt;filter-name&gt;characterEncodingFilter&lt;/filter-name&gt;</div><div class="line">   &lt;url-pattern&gt;/*&lt;/url-pattern&gt;</div><div class="line">&lt;/filter-mapping&gt;</div></pre></td></tr></table></figure>
<p>最后如果你要回显到页面上打印中文的话需要设置一下response<br>如果你使用springMVC可以设置  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">@RequestMapping(value = &quot;/XX.do&quot;, produces=&quot;text/html;charset=UTF-8&quot;)</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Encoding/" rel="tag"># Encoding</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/mysql-question-1/" rel="next" title="MySQL之order">
                <i class="fa fa-chevron-left"></i> MySQL之order
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/mysql-question-2/" rel="prev" title="改善Mac系统MySQL配置环境变量">
                改善Mac系统MySQL配置环境变量 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="zhangke" />
          <p class="site-author-name" itemprop="name">zhangke</p>
           
              <p class="site-description motion-element" itemprop="description">少点抱怨，多点改变</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/giantke" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/zkzk96871" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/5744544701?is_all=1" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#数据库层面"><span class="nav-number">1.</span> <span class="nav-text">数据库层面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Tomcat层面"><span class="nav-number">2.</span> <span class="nav-text">Tomcat层面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Web显示层面"><span class="nav-number">3.</span> <span class="nav-text">Web显示层面</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhangke</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhangk.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://zhangk.top/WebEncoding/';
          this.page.identifier = 'WebEncoding/';
          this.page.title = 'MySQL解决中文乱码之全套方案';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhangk.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  








  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lf4c0Nyki0bS0rlbFrB6xCkL-gzGzoHsz", "60Izmo6LzUMvv9zI4ABpYWhx");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
